package com.tanhua.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.commons.utils.JwtUtils;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter {

    @Value("${gateway.excludedUrls}")
    private String excludedUrls;

    /**
     * 方法作用：统一是否带有token过来，并且校验token的合法性。
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.获取请求路径，判断请求路径是否是直接放行的，如果是直接放行的直接放行即可。
        String path = exchange.getRequest().getURI().getPath(); //得到用户的请求路径
        List<String> excludedUrlsList = Arrays.asList(excludedUrls.split(","));
        if(excludedUrlsList.contains(path)){
            //放行的路径如果包含了本次的请求路径，直接放行
            return chain.filter(exchange);
        }

        //2. 如果不是直接放行的url我们就检查token，但是需要防止后台系统过来的token是带有Bearer
        String token = request.getHeaders().getFirst("Authorization");
        if(!StringUtils.isEmpty(token)){
            token = token.replaceAll("Bearer ","");
        }
        //3. 校验token的合法性，如果不合法返回响应数据即可。
        if(!JwtUtils.verifyToken(token)){
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("errorCode",401);
            resultMap.put("errMessage","没有登录");
            try {
                response.getHeaders().set("content-type","application/json;charset=utf-8");
                byte[] bytes = new ObjectMapper().writeValueAsBytes(resultMap);
                DataBuffer databuf = response.bufferFactory().wrap(bytes);
                return response.writeWith(Mono.just(databuf));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        //4. 如果合法直接放行。
        return chain.filter(exchange);
    }
}
